package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.WaterSalts;

public class WaterSaltsPresenter extends AbstractPresenter<WaterSalts> {
	final String SINGLEITEM = "waterSalts";
	final String MULTIITEM = "waterSaltss";
	
	public ArrayList<WaterSalts> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public WaterSalts tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public WaterSalts createItemFromJSONObject(JSONObject jsonObject){
		WaterSalts item = new WaterSalts();
		try{
			item.setCa(jsonObject.getDouble("ca"));
			item.setCl(jsonObject.getDouble("cl"));
			item.setCo3(jsonObject.getDouble("co3"));
			item.setCommonName(jsonObject.getString("commonName"));
			item.setMg(jsonObject.getDouble("mg"));
			item.setMolecularName(jsonObject.getString("molecularName"));
			item.setNa(jsonObject.getDouble("na"));
			item.setSaltID(jsonObject.getInt("saltID"));
			item.setSciName(jsonObject.getString("sciName"));
			item.setSo4(jsonObject.getDouble("so4"));
			
			if(!jsonObject.isNull("supID")){
				//create product if set
				SuppliesPresenter presenter = new SuppliesPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("supID");
				item.setSupply(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setSupply(null);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(WaterSalts item){
		try{
			JSONObject json = new JSONObject();
			json.put("ca", item.getCa());
			json.put("cl", item.getCl());
			json.put("co3", item.getCo3());
			json.put("commonName", item.getCommonName());
			json.put("mg", item.getMg());
			json.put("molecularName", item.getMolecularName());
			json.put("na", item.getNa());
			json.put("saltID", item.getSaltID());
			json.put("sciName", item.getSciName());
			json.put("so4", item.getSo4());
			if(item.getSupply()!=null){
				SuppliesPresenter presenter = new SuppliesPresenter();
				json.put("supID", presenter.createJSON(item.getSupply()));
			} else {
				json.put("supID", JSONObject.NULL);
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public WaterSalts getEmptyEntity(){
		WaterSalts entity = new WaterSalts();
		return entity;
	}
}
